from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json

mcp = FastMCP("Tuned MCP Server")

"""
面向 tuned 软件的 MCP Server

MCP tools 列表：
1. tuned_service_restart - 重启 tuned 服务
   参数：无
   返回：{"success": bool, "command": str, "exit_code": int, "stdout": str, "stderr": str}

2. tuned_service_reload - 重载 tuned 服务
   参数：无
   返回：{"success": bool, "command": str, "exit_code": int, "stdout": str, "stderr": str}
"""

@mcp.tool()
def tuned_service_restart() -> dict:
    """
    重启 tuned 服务
    
    参数：无
    
    返回 JSON 结构：
    {
        "success": bool,      # 命令是否成功执行
        "command": str,       # 执行的完整命令
        "exit_code": int,     # 命令退出码
        "stdout": str,        # 标准输出内容
        "stderr": str         # 标准错误内容
    }
    """
    command = ["systemctl", "restart", "tuned.service"]
    result = subprocess.run(command, capture_output=True, text=True)
    
    return {
        "success": result.returncode == 0,
        "command": " ".join(command),
        "exit_code": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr
    }

@mcp.tool()
def tuned_service_reload() -> dict:
    """
    重载 tuned 服务
    
    参数：无
    
    返回 JSON 结构：
    {
        "success": bool,      # 命令是否成功执行
        "command": str,       # 执行的完整命令
        "exit_code": int,     # 命令退出码
        "stdout": str,        # 标准输出内容
        "stderr": str         # 标准错误内容
    }
    """
    command = ["systemctl", "reload", "tuned.service"]
    result = subprocess.run(command, capture_output=True, text=True)
    
    return {
        "success": result.returncode == 0,
        "command": " ".join(command),
        "exit_code": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr
    }

if __name__ == "__main__":
    mcp.run()